﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Model;
using Bll;
using Common;
using System.IO;
using Microsoft.AspNetCore.Hosting;
using Web.Extension;
using Web.Jwt;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Authorization;
using Web.Util;
using System.Security.Claims;
using Web.Security;
using System.Drawing.Imaging;
using hyjiacan.py4n;
using Weixin;
using Newtonsoft.Json;
using System.Net.Http;
using Quartz;
using Web.Filter;

namespace Web.Controllers
{
    /// <summary>
    /// 好老师。常用的接口
    /// </summary>
    [Route("api/")]
    [ApiController]
    public class DefaultController : MyBaseController
    {
        private readonly IWebHostEnvironment webHostEnvironment;
        private readonly JwtConfig jwtConfig;
        public IUserBll userBll { get; set; }//通过属性依赖注入
        public IStudentBll studentBll { get; set; }
        public ITeacherBll teacherBll { get; set; }
        public IImageBll imageBll { get; set; }
        //  public IClaimsAccessor MyUser { get; set; }
        IConfiguration configuration { get; set; }
        private IHttpClientFactory _httpClientFactory; //注入HttpClient工厂类

        /// <summary>
        /// 获取http请求
        /// </summary>
        private HttpHelper1 httpHelper = null;

        private IOptions<WxConfig> wxConfig;
        public DefaultController(IWebHostEnvironment webHostEnvironment, IConfiguration configuration, IOptions<JwtConfig> jwtConfig, IOptions<WxConfig> wxConfig, IHttpClientFactory httpClientFactory)
        {
            this.webHostEnvironment = webHostEnvironment;
            this.jwtConfig = jwtConfig.Value;
            this.configuration = configuration;
            this.wxConfig = wxConfig;
            httpHelper = new HttpHelper1();
            _httpClientFactory = httpClientFactory;
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="o">接收username、password、type三个参数</param>
        /// <returns></returns>
        // POST: api/login
        [HttpPost("login")]
        //public Result Login([FromForm] Userinfo o)
        public Result Login(Userinfo o)
        //public Result Login([FromForm]string username, [FromForm]string password,[FromForm]string type="student")
        {
            string project = "", type = "";
            int classid = 0, schoolid = 0;
            Person obj = null;
            if (o.Type == RoleType.teacher.ToString())
            {
                obj = teacherBll.Login(o.Username, o.Password);
            }
            else if (o.Type == RoleType.student.ToString())
            {
                obj = studentBll.Login(o.Username, o.Password);
                if (obj != null)
                {
                    project = ((Student)obj).ClasssId.ToString();
                    classid = ((Student)obj).ClasssId;
                }
            }
            else
            {
                obj = userBll.Login(o.Username, o.Password);
            }
            if (obj != null)
            {
                type = o.Type;
                var t = new Token() { Uid = obj.Id, Uname = obj.Username, Role = obj.Role, Type = type, TokenType = TokenType.App, Project = project, ClasssId = classid, SchoolId = schoolid };
                return Result.Success("登录成功")
                    .SetData(new Userinfo() { Id = obj.Id, Username = obj.Username, Avatar = obj.Photo, Role = obj.Role, Type = o.Type, Realname = obj.Realname, Tel = obj.Tel, Email = obj.Email, Birthday = obj.Birthday, Token = JwtHelper.IssueJWT(t, this.jwtConfig) });
                //return Result.Success("登录成功").SetData(new Userinfo() { Token = "admin" });
            }
            return Result.Error("登录失败,用户名密码错误").SetData(new Userinfo() { Token = "" });
        }
        /// <summary>
        /// 微信小程序登录
        /// </summary>
        /// <param name="code"></param>
        /// <param name="username"></param>
        /// <param name="avatar"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        [HttpPost("snslogin")]
        public Result SnsLogin([FromForm] string code, [FromForm]string username, [FromForm]string avatar, string type = "user")
        {
            string Appid = wxConfig.Value.Mini.AppID;
            string AppSecret = wxConfig.Value.Mini.AppSecret;
            var url = $"https://api.weixin.qq.com/sns/jscode2session?appid={Appid}&secret={AppSecret}&js_code={code}&grant_type=authorization_code";
            //HttpItem item = new HttpItem
            //{
            //    URL = $"https://api.weixin.qq.com/sns/jscode2session?appid={Appid}&secret={AppSecret}&js_code={code}&grant_type=authorization_code"
            //};           
            var httpHelper = new HttpHelper(_httpClientFactory);
            var jObject = JsonConvert.DeserializeObject<Code2SessionResult>(httpHelper.Get(url, null, null).Result);
            if (!string.IsNullOrEmpty(jObject.openid))
            {
                //微信用户
                var obj = userBll.SelectOne(o => o.Wx_openid == jObject.openid);
                if (obj == null)//先注册
                {
                    obj = new User() { Username = username, Pswd = username, Wx_openid = jObject.openid, Photo = avatar, Role = "user", Sys = false };
                    userBll.Add(obj);
                }
                //绑定类型
                if (obj.Student != null)
                {
                    var student = obj.Student;
                    Console.WriteLine(JsonConvert.SerializeObject(student));
                    //以另一种身份登录
                    var t = new Token() { Uid = student.Id, Uname = student.Username, Role = student.Role, TokenType = TokenType.App, Project = Convert.ToString(student.ClasssId), Type = RoleType.student.ToString(), ClasssId = student.ClasssId, SchoolId = student.Classs.SchoolId };
                    return Result.Success("登录成功")
                        .SetData(new Userinfo() { Id = student.Id, Username = student.Username, Avatar = student.Photo, Role = student.Role, Type = RoleType.student.ToString(), Realname = student.Realname, Tel = student.Tel, Email = student.Email, Birthday = student.Birthday, Token = JwtHelper.IssueJWT(t, this.jwtConfig), ClasssId = student.ClasssId, SchoolId = student.Classs.SchoolId });
                }
                else if (obj.Teacher != null)
                {
                    var teacher = obj.Teacher;
                    //以另一种身份登录
                    var t = new Token() { Uid = teacher.Id, Uname = teacher.Username, Role = teacher.Role, TokenType = TokenType.App, Type = RoleType.teacher.ToString(), ClasssId = 0, SchoolId = teacher.SchoolId };
                    return Result.Success("登录成功")
                        .SetData(new Userinfo() { Id = teacher.Id, Username = teacher.Username, Avatar = teacher.Photo, Role = teacher.Role, Type = RoleType.teacher.ToString(), Realname = teacher.Realname, Tel = teacher.Tel, Email = teacher.Email, Birthday = teacher.Birthday, Token = JwtHelper.IssueJWT(t, this.jwtConfig), ClasssId = 0, SchoolId = teacher.SchoolId });
                }
                else//普通会员登录
                {
                    var t = new Token() { Uid = obj.Id, Uname = obj.Username, Role = obj.Role, TokenType = TokenType.App, Project = "", Type = RoleType.user.ToString(), ClasssId = 0, SchoolId = 0 };
                    return Result.Success("登录成功")
                        .SetData(new Userinfo() { Id = obj.Id, Username = obj.Username, Avatar = obj.Photo, Role = obj.Role, Type = RoleType.user.ToString(), Realname = obj.Realname, Tel = obj.Tel, Email = obj.Email, Birthday = obj.Birthday, Token = JwtHelper.IssueJWT(t, this.jwtConfig) });
                    //return Result.Success("登录成功").SetData(new Userinfo() { Token = "admin" });
                }
            }
            return Result.Error("登录失败" + jObject.errmsg);
        }
        /// <summary>
        /// 登录绑定
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        [HttpPost("loginbind")]
        [Authorize]
        public Result LoinBind([FromForm]string username, [FromForm]string password, string type = "student")
        {
            var obj = userBll.SelectOne(o => o.Id == MyUser.Id);
            //绑定类型
            if ("student" == type)
            {
                var student = studentBll.Login(username, password);
                if (student == null)
                {
                    return Result.Error("绑定失败,账号密码错误");
                }
                obj.Student = student;
                //修改
                userBll.Update(obj);
                //以另一种身份登录
                var t = new Token() { Uid = student.Id, Uname = student.Username, Role = student.Role, TokenType = TokenType.App, Project = Convert.ToString(student.ClasssId), Type = RoleType.student.ToString(), ClasssId = student.ClasssId, SchoolId = student.Classs.SchoolId };
                return Result.Success("登录成功")
                    .SetData(new Userinfo() { Id = student.Id, Username = student.Username, Avatar = student.Photo, Role = student.Role, Type = type, Realname = student.Realname, Tel = student.Tel, Email = student.Email, Birthday = student.Birthday, Token = JwtHelper.IssueJWT(t, this.jwtConfig), ClasssId = student.ClasssId, SchoolId = student.Classs.SchoolId });
            }
            else
            {
                var teacher = teacherBll.Login(username, password);
                if (teacher == null)
                {
                    return Result.Error("绑定失败,账号密码错误");
                }
                obj.Teacher = teacher;
                //修改
                userBll.Update(obj);
                //以另一种身份登录
                var t = new Token() { Uid = teacher.Id, Uname = teacher.Username, Role = teacher.Role, TokenType = TokenType.App, Type = RoleType.teacher.ToString(), ClasssId = 0, SchoolId = teacher.SchoolId };
                return Result.Success("登录成功")
                    .SetData(new Userinfo() { Id = teacher.Id, Username = teacher.Username, Avatar = teacher.Photo, Role = teacher.Role, Type = type, Realname = teacher.Realname, Tel = teacher.Tel, Email = teacher.Email, Birthday = teacher.Birthday, Token = JwtHelper.IssueJWT(t, this.jwtConfig), ClasssId = 0, SchoolId = teacher.SchoolId });
            }
        }
        // GET: api/getuserinfo
        /// <summary>
        /// 获取登录信息
        /// </summary>
        /// <returns></returns>
        [HttpGet("getuserinfo")]
        [Authorize]
        public Result GetUserinfo()
        {
            Person obj = null;
            if (MyUser.Role.StartsWith(RoleType.teacher.ToString()))
            {
                obj = teacherBll.SelectOne(MyUser.Id);
            }
            else if (MyUser.Role.StartsWith(RoleType.student.ToString()))
            {
                obj = studentBll.SelectOne(MyUser.Id);
            }
            else
            {
                obj = this.userBll.SelectOne(MyUser.Id);
            }
            if (obj != null)
            {
                obj.Pswd = "";
                return Result.Success("获取成功").SetData(obj);
            }
            return Result.Error("获取失败").SetData(new Userinfo() { });
        }

        private string[] imgExt = { ".jpg", ".jpeg", ".png", ".gif" };
        private int imgSizeLimit = 500 * 1024;
        /// <summary>
        /// 图片上传
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost("imgupload")]
        //[IdentityModel] 
        [Authorize]
        public async Task<Result> ImgUpload(IFormFile file)
        {
            var ext = Path.GetExtension(file.FileName).ToLowerInvariant();
            if (string.IsNullOrEmpty(ext) || !imgExt.Contains(ext))
            {
                return Result.Error("上传失败,请选择jpg|jpeg|png|gif类型图片");
            }
            if (file.Length > 0)
            {
                if (file.Length > imgSizeLimit)
                {
                    var size = imgSizeLimit / 1024;
                    return Result.Error($"上传失败,文件超过大小{size}KB");
                }
                //汉字转拼音
                //string filename = Pinyin4Net.GetPinyin(file.FileName, PinyinFormat.LOWERCASE);
                string filePath = "/upload/" + Guid.NewGuid().ToString() + ext;
                //string phypath= webHostEnvironment.WebRootPath + filePath;
                //if (System.IO.File.Exists(phypath))
                // {
                //     Guid.NewGuid().ToString()
                // }
                Image o = new Image
                {
                    Name = file.FileName
                };
                if (MyUser.Type == RoleType.teacher.ToString())
                {
                    o.TeacherId = MyUser.Id;
                }
                else if (MyUser.Type == RoleType.student.ToString())
                {
                    o.StudentId = MyUser.Id;
                }
                else
                {
                    o.UserId = MyUser.Id;
                }
                //是否是系统上传
                if (MyUser.Role.StartsWith("admin") || MyUser.Role.StartsWith("school"))
                {
                    o.Sys = true;
                }
                else
                {
                    o.Sys = false;
                }
                o.Path = filePath;
                using (var stream = System.IO.File.Create(webHostEnvironment.WebRootPath + filePath))
                {
                    await file.CopyToAsync(stream);
                }
                imageBll.Add(o);
                return Result.Success("上传成功").SetData(o);
            }
            else
            {
                return Result.Success("上传失败,空文件");
            }
        }
        /// <summary>
        /// 生成二维码图片
        /// </summary>
        /// <param name="text"></param>
        /// <param name="size">生成二维码图片的像素大小</param>
        // [HttpGet("qrcode/{text}/{size}")]
        [HttpGet("qrcode")]
        public void GetQRCode(string text, int size = 5)
        {
            Response.ContentType = "image/jpeg";
            var bitmap = QRCodeHelper.GetQRCode(text, size);
            MemoryStream ms = new MemoryStream();
            bitmap.Save(ms, ImageFormat.Jpeg);
            Response.Body.WriteAsync(ms.GetBuffer(), 0, Convert.ToInt32(ms.Length));
            Response.Body.Close();
        }
        /// <summary>
        /// APP更新检查
        /// </summary>
        /// <param name="appid"></param>
        /// <param name="version"></param>
        /// <param name="imei"></param>
        /// <param name="platform"></param>
        /// <param name="source"></param>
        /// <returns></returns>
        [HttpGet("app_update")]
        //[Route("app_update")]
        public Result AppUpdate(string appid, string version, string imei, string platform, string source)
        {
            if ("haolaoshi" == source)
            {
                var v = configuration["App:hls:version"];
                var m = configuration["App:hls:msg"];
                var u = configuration["App:hls:url"];
                if (Convert.ToInt32(v) > Convert.ToInt32(version))
                { //遗留版本
                    return Result.Success("有新版本啦，要更新吗").SetData(new { msg = m, url = u });
                }
                return Result.Error("无更新版本");
            }
            else
            {
                var v = configuration["App:hxs:version"];
                var m = configuration["App:hxs:msg"];
                var u = configuration["App:hxs:url"];
                if (Convert.ToInt32(v) > Convert.ToInt32(version))
                { //遗留版本
                    return Result.Success("有新版本啦，要更新吗").SetData(new { msg = m, url = u });
                }
                return Result.Error("无更新版本");
            }

        }
        [HttpGet("test")]
        public Result Test()
        {
            // Console.WriteLine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase);
            // NLogHelper.logger.Error("XXX");
            return Result.Error("测试");
        }
    }
}

